/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.entity.MaintainPlanContentPersonnel;
import org.springblade.modules.admin.entity.MaintainPlanContentUser;
import org.springblade.modules.admin.entity.MaintainSign;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.MaintainPlanContentStatusEnum;
import org.springblade.modules.admin.enums.StatusEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.IMaintainPlanContentUserService;
import org.springblade.modules.admin.service.IMaintainSignService;
import org.springblade.modules.admin.service.MaintainPlanContentPersonnelService;
import org.springblade.modules.admin.vo.plan.PlanUserSignDetailVo;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 维保任务关联人员中间表 控制器
 *
 * @author BladeX
 * @since 2021-05-10
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/maintainPlanContentUser")
@Api(value = "维保任务关联人员中间表", tags = "维保任务关联人员中间表接口")
@Slf4j
public class MaintainPlanContentUserController extends BladeController {

	private final IMaintainPlanContentUserService maintainPlanContentUserService;

	private final IMaintainPlanContentService maintainPlanContentService;

	private final MaintainPlanContentPersonnelService planContentPersonnelService;

	private final IDeptService deptService;

	private final IRoleService roleService;

	private final IUserService userService;

	private final IMaintainSignService maintainSignService;

	/**
	 * 详情
	 */
	@GetMapping("/plan/user/headImg")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取工单头像", notes = "传入maintainPlanContentUser")
	public R<List<PlanUserSignDetailVo>> detail(Long planId) {
		MaintainPlanContent planContent = maintainPlanContentService.getById(planId);
		if (planContent == null) {
			throw new ServiceException("工单id错误找不到对应的工单");
		}
		List<PlanUserSignDetailVo> signUsers = new ArrayList<>(16);
		List<PlanUserSignDetailVo> resultList = new ArrayList<>(16);
		List<MaintainPlanContentUser> contentUserList = maintainPlanContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, planId));
		for (MaintainPlanContentUser maintainPlanContentUser : contentUserList) {
			PlanUserSignDetailVo signUser = maintainPlanContentUser.getSignUser();
			if (signUser == null) {
				continue;
			}
			final User user = userService.getById(maintainPlanContentUser.getUserId());
			String deptId = user.getDeptId();
			List<String> names = deptService.listByIds(Arrays.asList(deptId.split(","))).stream().map(Dept::getDeptName).collect(Collectors.toList());
			signUser.setDeptName(names);
			signUsers.add(signUser);
		}
		if (!planContent.getStatus().equals(TaskStatusEnum.BY_PROCESSED.getStatus())) {
			if (signUsers.size() > 0) {
				for (PlanUserSignDetailVo planUserSignDetailVo : signUsers) {
					if (!planUserSignDetailVo.getIsTakePartIn()) {
						resultList.add(planUserSignDetailVo);
					}
				}
			}
		}
		signUsers.removeAll(resultList);
		return R.data(signUsers);
	}


	@PostMapping("/saveBatch")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "批量分配人员")
	public R<Boolean> saveBatch(@RequestBody List<MaintainPlanContentUser> list) {
		final List<MaintainPlanContentUser> contentUsers = list.stream().filter(o -> o.getStatus() == null).collect(Collectors.toList());
		maintainPlanContentUserService.addBatch(contentUsers);
		return R.data(true);
	}

	@PostMapping("/list")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取分配人员")
	public R<List<MaintainPlanContentUser>> list(@RequestBody List<Long> planIds) {
		final List<MaintainPlanContentUser> planContentUserList = maintainPlanContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().in(MaintainPlanContentUser::getPlanId, planIds));
		for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
			User user = userService.getById(maintainPlanContentUser.getUserId());
			if (user.getRoleId() != null) {
				List<String> roids = Arrays.asList(user.getRoleId().split(","));
				List<String> roleNames = roleService.listByIds(roids).stream().map(Role::getRoleName).collect(Collectors.toList());
				maintainPlanContentUser.setRoleNames(roleNames);
			}
			maintainPlanContentUser.setUserName(user.getRealName());
			List<MaintainSign> signList = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainSign::getUserId, maintainPlanContentUser.getUserId()));
			maintainPlanContentUser.setStatus(signList.size() > 0 ? StatusEnum.ENABLE.getId() : StatusEnum.DISABLE.getId());
		}
		return R.data(planContentUserList);
	}


	@GetMapping("/list/v2")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取分配人员")
	public R<List<MaintainPlanContentUser>> listV2(Long planId) {

		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(planId);
		if (maintainPlanContent.getStatus().equals(TaskStatusEnum.BY_DISABLE.getStatus()) || maintainPlanContent.getStatus().equals(TaskStatusEnum.BY_PROCESSED.getStatus())) {
			List<MaintainPlanContentUser> planContentUserList = maintainPlanContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, planId));
			for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
				maintainPlanContentUser.setUserName(userService.getById(maintainPlanContentUser.getUserId()).getRealName());
				maintainPlanContentUser.setDeptNames(userService.getDeptNames(maintainPlanContentUser.getUserId()));
				List<MaintainSign> signList = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainSign::getUserId, maintainPlanContentUser.getUserId()));
				maintainPlanContentUser.setStatus(signList.size() > 0 ? StatusEnum.ENABLE.getId() : StatusEnum.DISABLE.getId());
			}
			return R.data(planContentUserList);
		}
		List<MaintainPlanContentPersonnel> list = planContentPersonnelService.list(Wrappers.<MaintainPlanContentPersonnel>lambdaQuery().eq(MaintainPlanContentPersonnel::getPlanId, planId));
		List<MaintainPlanContentUser> planContentUserList = new ArrayList<>(16);
		for (MaintainPlanContentPersonnel maintainPlanContentPersonnel : list) {
			MaintainPlanContentUser maintainPlanContentUser = new MaintainPlanContentUser();
			maintainPlanContentUser.setUserName(userService.getById(maintainPlanContentPersonnel.getUserId()).getRealName());
			maintainPlanContentUser.setDeptNames(userService.getDeptNames(maintainPlanContentPersonnel.getUserId()));
			planContentUserList.add(maintainPlanContentUser);
		}
		return R.data(planContentUserList);
	}

	@PostMapping("/delete")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "删除分配人员")
	public R<Boolean> delete(@RequestBody List<MaintainPlanContentUser> list) {

		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(list.get(0).getPlanId());
		if (maintainPlanContent.getTypeStatus() == MaintainPlanContentEnum.MAINTAIN_BY.getId() || maintainPlanContent.getTypeStatus() == MaintainPlanContentEnum.MAINTAIN_PARTS.getId()) {
			for (MaintainPlanContentUser maintainPlanContentUser : list) {
				final List<MaintainSign> signList = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainSign::getUserId, maintainPlanContentUser.getUserId()));
				if (signList.size() > 0) {
					throw new ServiceException("该用户存在签到信息不能删除");
				} else {
					maintainPlanContentUserService.remove(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainPlanContentUser::getUserId, maintainPlanContentUser.getUserId()));
				}
			}
		} else if (maintainPlanContent.getTypeStatus() == MaintainPlanContentEnum.MAINTAIN_KR.getId()) {
			if (maintainPlanContent.getStatus() == TaskStatusEnum.JY_PROCESSED.getStatus()) {
				List<MaintainPlanContentUser> userList = maintainPlanContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, maintainPlanContent.getId()));
				if (userList.size() > 0) {
					final List<Long> userIds = userList.stream().map(MaintainPlanContentUser::getUserId).collect(Collectors.toList());
					for (MaintainPlanContentUser user : list) {
						if (userIds.contains(user.getUserId())) {
							throw new ServiceException("包含不能删除的人员,请重新选择");
						} else {
							maintainPlanContentUserService.remove(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, user.getPlanId()).eq(MaintainPlanContentUser::getUserId, user.getUserId()));
						}
					}
				}
			}
		} else if (maintainPlanContent.getTypeStatus() == MaintainPlanContentEnum.MAINTAIN_WX.getId()) {
			for (MaintainPlanContentUser maintainPlanContentUser : list) {
				final List<MaintainSign> signList = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainSign::getUserId, maintainPlanContentUser.getUserId()));
				if (signList.size() > 0) {
					throw new ServiceException("该用户存在签到信息不能删除");
				} else {
					maintainPlanContentUserService.remove(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainPlanContentUser::getUserId, maintainPlanContentUser.getUserId()));
				}
			}
		} else if (maintainPlanContent.getTypeStatus() == MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId()) {
			for (MaintainPlanContentUser maintainPlanContentUser : list) {
				final List<MaintainSign> signList = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainSign::getUserId, maintainPlanContentUser.getUserId()));
				if (signList.size() > 0) {
					throw new ServiceException("该用户存在签到信息不能删除");
				} else {
					maintainPlanContentUserService.remove(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, maintainPlanContentUser.getPlanId()).eq(MaintainPlanContentUser::getUserId, maintainPlanContentUser.getUserId()));
				}
			}
		}

		return R.data(true);
	}

}
